package com.cxyjy.cfyuiapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cxyjy.cfyuiapi.service.PromptWorkflowService;
import com.cxyjy.cfyuiapi.service.UploadImageService;
import com.cxyjy.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.cxyjy.common.constants.CfyuiConstants.BAIDU_EXPECTED_IMAGE_EXTENSIONS;
import static com.cxyjy.common.util.JObjectUtil.stringValue;
import static com.cxyjy.common.util.ResultCode.*;
import static com.cxyjy.common.util.ResultUtil.error;
import static com.cxyjy.common.util.ResultUtil.success;

@RestController
public class UploadImageController {
    @Autowired
    UploadImageService uploadImageService;
    @Autowired
    PromptWorkflowService promptWorkflowService;

    /**
     * 目前demo在用的上传图片接口
     * 接收前端上传的图片,格式只支持jpg、png、jpeg
     *
     * @param image
     * @return
     */
    @PostMapping("/uploadFaceSwapImage")
    public JResponse uploadFaceSwapImage(@RequestParam(required = false) MultipartFile image, @RequestParam(required = false) String url) throws IOException {
        //二选一校验：必须传image或url，且不能同时传
        if ((image == null && url == null) || (image != null && url != null)) {
            return ResultUtil.error(FACESWAP_EXCLUSIVE_PARAMETERS_PROVIDED);
        }
        if (image != null) {
            if (image.isEmpty() || image.getOriginalFilename() == null) {
                return ResultUtil.error(NO_IMAGE_FOUNDED);
            }
            if (!JFileUtil.checkFileExtension(image, BAIDU_EXPECTED_IMAGE_EXTENSIONS)) {
                return ResultUtil.error(NO_IMAGE_FOUNDED);
            }
        } else if (!JFileUtil.isImageUrl(url)) {
            return ResultUtil.error(NO_IMAGE_FOUNDED);
        }
        String fileName = image != null ? uploadImageService.uploadFaceSwapImage(image) : uploadImageService.uploadFaceSwapImage(url);
        if (!fileName.contains(".")) {
            //这种情况fileName实际是错误代码
            return ResultUtil.error(ResultCode.find(JObjectUtil.objectToInt(fileName)));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("imageFileName", fileName);
        return success(resultMap);
    }

    /**
     * 将目标图片(targetImage)中的人脸换为模板图片(sourceImage)中的人脸
     *
     * @param targetImage
     * @param sourceImage
     * @param targetImageUrl
     * @param sourceImageUrl
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadImageFaceSwapImage")
    public JResponse uploadImageFaceSwapImage(@RequestParam(required = false) MultipartFile targetImage,
                                              @RequestParam(required = false) MultipartFile sourceImage,
                                              @RequestParam(required = false) String targetImageUrl,
                                              @RequestParam(required = false) String sourceImageUrl) throws IOException {
        JSONObject responseJSONObject = new JSONObject();
        // 情况一：使用本地上传的图片
        if ((targetImage != null && sourceImage != null) && (targetImageUrl == null && sourceImageUrl == null)) {
            // 合法情况，继续处理
            String targetImageName = uploadImageService.uploadFaceSwapImage(targetImage);
            String sourceImageName = uploadImageService.uploadFaceSwapImage(sourceImage);
            responseJSONObject.put("targetImageName", targetImageName);
            responseJSONObject.put("sourceImageName", sourceImageName);
            return success(responseJSONObject);
        }

        // 情况二：使用远程图片链接
        else if ((targetImageUrl != null && sourceImageUrl != null) && (targetImage == null && sourceImage == null)) {
            // 合法情况，继续处理
            if(!JFileUtil.isImageUrl(targetImageUrl)||!JFileUtil.isImageUrl(sourceImageUrl)){
                return error(NO_IMAGE_FOUNDED);
            }
            Map<String, Object> fileNameResultMap = uploadImageService.uploadImageFaceSwapImage(targetImageUrl, sourceImageUrl);
            responseJSONObject.put("targetImageName", stringValue(fileNameResultMap.get("targetImageFileName")));
            responseJSONObject.put("sourceImageName", stringValue(fileNameResultMap.get("sourceImageFileName")));
            return success(responseJSONObject);
        }

        // 其他所有参数乱传的情况都是非法的
        else {
            return error(FACESWAP_EXCLUSIVE_PARAMETERS_PROVIDED);
        }
    }

    /**
     * @param multipartFile
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadImageBinaryToComfyUI")
    public JResponse uploadImageBinaryToComfyUI(@RequestParam(name = "image") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile == null) {
            return ResultUtil.error(FILE_NOT_FOUND);
        }
        Object o = uploadImageService.uploadImageBinaryToComfyUI(multipartFile, request);
        return success(o);
    }


}
